//
//  DetailSwipeView.m
//  PriceOnline
//
//  Created by Tai Le on 6/24/13.
//  Copyright (c) 2013 WorkLikeDance. All rights reserved.
//

#import "ControllersSwipeView.h"
#import "Utility.h"

@implementation ControllersSwipeView

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self initSubViews];
        _selectedIndex = -1;
    }
    
    return self;
}

- (void)initSubViews
{
    _currentView = [[ControllersSwipeViewItem alloc] initWithFrame:RECT(0, 0, self.width, self.height)];
    _currentView.parentSwipeView = self;
    [self addSubview:_tempView];
    
    _tempView = [[ControllersSwipeViewItem alloc] initWithFrame:RECT(0, 0, self.width, self.height)];
    _tempView.parentSwipeView = self;
    [self addSubview:_currentView];
    
    self.backgroundColor = [UIColor whiteColor];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
    [self addGestureRecognizer:panGesture];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    [_currentView setFrame:RECT(_currentView.left, 0, self.width, self.height)];
    [_tempView setFrame:RECT(_tempView.left, _currentView.top, _currentView.width, _currentView.height)];
}

- (void)setDelegate:(id<ControllersSwipeViewDelegate>)delegate
{
    _delegate = delegate;
    [self setSelectedIndex:0];
}

-(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPathRef path = CGPathCreateWithRect(CGRectMake(0, 0, self.width, self.height), NULL);
    [[UIColor redColor] setFill];
    [[UIColor greenColor] setStroke];
    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathFillStroke);
    CGPathRelease(path);
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    if (_selectedIndex == selectedIndex)
    {
        return;
    }
    
    if (selectedIndex > -1)
    {
        _selectedIndex = selectedIndex;
        [_currentView showViewController:[self viewControllerAtIndex:_selectedIndex]];
    }
}

- (BaseViewController*) viewControllerAtIndex:(NSInteger)index
{
    return [_delegate controllersSwipeView:self viewControllerAtIndex:index];
}

- (NSInteger) numberOfViewControllers
{
    return [_delegate numberOfViewControllers];
}

- (CGFloat)anchorLeftCenter
{
    return -self.bounds.size.width / 2;
}

- (CGFloat)anchorCenter
{
    return (self.bounds.size.width / 2);
}

- (CGFloat)anchorRightCenter
{
    return (self.bounds.size.width * 1.5);
}

- (void)moveTempViewInFront:(BOOL) isInFront
{
    if (isInFront)
    {
        [self addSubview:_currentView];
        [self addSubview:_tempView];
    }
    else
    {
        [self addSubview:_tempView];
        [self addSubview:_currentView];
    }
}

- (void)sweepCurrentAndTempView
{
    ControllersSwipeViewItem *temp = _currentView;
    _currentView = _tempView;
    _tempView = temp;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
    {
        
    }
    
    return YES;
}

- (void)panGestureHandler:(UIPanGestureRecognizer *)recognizer
{
    
    CGPoint currentTouchPoint     = [recognizer locationInView:self.superview];
    CGFloat curX = currentTouchPoint.x;
    
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        _preTouchX = curX;
    }
    else if (recognizer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat dx = curX - _preTouchX;
        //swipe right
        if (dx > 0)
        {
            if (_movingView == nil)
            {
                //moving item is self
                if ([self isFirstItem])
                {
                    return;
                }
                //moving item is currentView
                else
                {
                    [self moveTempViewInFront:NO];
                    NSInteger preIndex = [self previousIndex];
                    if (preIndex > -1)
                    {
                        CGPoint center = CGPointMake([self anchorCenter], _tempView.center.y) ;
                        _tempView.center = center;
                        
                        //load data
                        [_tempView showViewController:[self viewControllerAtIndex:preIndex]];
                    }
                    
                    _anchorTempLeft = [self anchorCenter];
                    _anchorTempRight = [self anchorRightCenter];
                    _movingView = _currentView;
                }
            }
        }
        //swipe left
        else
        {
            if (_movingView == nil)
            {
                //lastItem dont move
                if ([self isLastItem])
                {
                    return;
                }
                //moving item is under left
                else
                {
                    [self moveTempViewInFront:YES];
                    NSInteger nextIndex = [self nextIndex];
                    if (nextIndex > -1)
                    {
                        //load data
                        [_tempView showViewController:[self viewControllerAtIndex:nextIndex]];
                    }
                    
                    _movingView = _tempView;
                    _anchorTempLeft = [self anchorCenter];
                    _anchorTempRight = [self anchorRightCenter];
                }
                
                if (![_movingView isEqual:self])
                {
                    CGPoint center = CGPointMake([self anchorRightCenter], _movingView.center.y);
                    _movingView.center = center;
                }
            }
        }
        
        CGFloat newCenterPosition = _movingView.center.x + dx;
//        NSLog(@"center:%f, dx:%f",newCenterPosition, _movingView.center.x);
        if (newCenterPosition < _anchorTempLeft)
        {
            newCenterPosition = _anchorTempLeft;
        }
        else if(newCenterPosition > _anchorTempRight)
        {
            newCenterPosition = _anchorTempRight;
        }

        CGPoint center = CGPointMake(newCenterPosition, _movingView.center.y);

        _movingView.center = center;
        _preTouchX = curX;
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled)
    {
        CGPoint currentVelocityPoint = [recognizer velocityInView:self];
        CGFloat currentVelocityX     = currentVelocityPoint.x;
        //swiping right
        if (currentVelocityX > 0)
        {
//            NSLog(@"End swipe right");
            
            [self animationToX:self.anchorRightCenter velocity:currentVelocityX forView:_movingView];
            if ([_movingView isEqual:_currentView])
            {
                [self sweepCurrentAndTempView];
                _selectedIndex = [self previousIndex];
            }                            
        }
        //swiping left
        else
        {
//            NSLog(@"End swipe left");                        
            [self animationToX:self.anchorCenter velocity:currentVelocityX forView:_movingView];
            if ([_movingView isEqual:_tempView])
            {
                [self sweepCurrentAndTempView];
                _selectedIndex = [self nextIndex];
            }
        }
        _movingView = nil;
    }
}

- (void) animationToX:(CGFloat)x velocity:(CGFloat)vel forView:(UIView*)view
{
    CGFloat distant = abs(view.center.x - x);
    CGFloat time = [Utility estimateTimeWithDis:distant andVelocity:abs(vel)];
    [UIView animateWithDuration:time animations:^{
        view.center = CGPointMake(x, view.center.y);
    }
     completion:^(BOOL finished) {
         if ([_delegate respondsToSelector:@selector(controllersSwipeViewDidSwipe:)])
         {
             [_delegate controllersSwipeViewDidSwipe:self];
         }
     }];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    if (_tempView.left > 0)
    {
        [_tempView setFrame:RECT(frame.size.width, 0, self.width, self.height)];
    }
    else
    {
        [_tempView setFrame:RECT(_tempView.left, 0, self.width, self.height)];
    }
    
    [_currentView setFrame:RECT(_currentView.left, 0, self.width, self.height)];    
}

- (BOOL) isLastItem
{
    return _selectedIndex == [self numberOfViewControllers] - 1;
}

- (BOOL) isFirstItem
{
    return _selectedIndex == 0;
}

- (NSInteger) nextIndex
{
    if (_selectedIndex < [self numberOfViewControllers] - 1)
    {
        return _selectedIndex + 1;
    }
    
    return -1;
}

- (NSInteger) previousIndex
{
    if (_selectedIndex > -1)
    {
        return _selectedIndex - 1;
    }
    return _selectedIndex - 1;
}

@end
